package battleship;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(description = "Compresses resources with gzip.",
//        servletNames ="*",
//        urlPatterns = { "*.*" })
//        urlPatterns = { "*.css", "*.js", "*.png" })
public class GzipFilter implements Filter {

    public void init(FilterConfig conf) {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException{

        if (req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;

            String encodings = request.getHeader("accept-encoding");
            if (encodings != null && encodings.contains("gzip")) {
                System.out.println("GZIP supported, compressing.");
                GzipResponseWrapper wrappedResponse = new GzipResponseWrapper(response);
                chain.doFilter(req, wrappedResponse);
                wrappedResponse.finishResponse();
                return;
            }

            chain.doFilter(req, resp);
        }
    }

    public void destroy() {

    }
}
